﻿using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System;
using System.Collections;
namespace anim3
{
    // UI 基类，封装通用的 UI 操作
    public class UIBase : MonoBehaviour
    {
        protected Animator animator;
        protected bool isOpen = false;

        protected virtual void Awake()
        {
            animator = GetComponent<Animator>();
        }

        // 打开 UI 并播放打开动画
        public virtual void Open()
        {
            gameObject.SetActive(true);
           // animator.SetTrigger("Open");
            isOpen = true;
        }

        // 关闭 UI 并播放关闭动画
        public virtual void Close(Action onCloseComplete = null)
        {
            //  StartCoroutine(WaitAnim());
            //animator.SetTrigger("Close");
            //isOpen = false;

            if (animator != null)
            {
                StartCoroutine(WaitAnim(onCloseComplete));
            }
            else
            {
                gameObject.SetActive(false);
                onCloseComplete?.Invoke();
            }
        }
        private void OnCloseAnimationComplete()
        {
            gameObject.SetActive(false);
        }

        // 动画结束回调，可根据需求重写
        public virtual void OnAnimationEnd()
        {
            //  if (!isOpen)
            {
                // UIManager.Instance.CloseUI("Panel1");
                gameObject.SetActive(false);
            }
        }
        public IEnumerator WaitAnim(Action onCloseComplete)
        {
            animator.SetTrigger("Close");
            float timeFloat = Array.Find(animator.runtimeAnimatorController.animationClips, clip => clip.name == "Exit").length;


            yield return new WaitForSeconds(timeFloat);

            OnCloseAnimationComplete();
            onCloseComplete?.Invoke();


            animator.SetTrigger("Exit"); // 触发动画

            //float timeFloat = Array.Find(animator.runtimeAnimatorController.animationClips, clip => clip.name == "Exit").length;
            //yield return new WaitForSeconds(timeFloat);
            //isOpen = false;
            //OnAnimationEnd();

        }


    }
}